package com.example.sangong.utils;

import com.example.sangong.entity.Player;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.List;


/**
 * 积分清算工具类
 */
@Slf4j
public class ScoreUtils {


    public static void storeScore(Player master, List<Player> followerList) {


        for (Player player : followerList) {
            int credit = RuleUtils.calCredit(master.getScoreEnum(), player.getScoreEnum(), player.getChip());
            player.setCredit(credit);

        }

        //先排序，输的得玩家优先，然后倍数大的优先
        Collections.sort(followerList, (o1, o2) -> {
            int result = o2.getCredit() - o1.getCredit();
            if (result != 0) {
                return result;
            }
            return o2.getScoreEnum().getPoints() - o1.getScoreEnum().getPoints();


        });
        for (Player player : followerList) {
//            int credit = RuleUtils.calCredit(master.getScoreEnum(), player.getScoreEnum(), player.getChip());
            int finalCredit = calFinalCredit(master.getScore(), player.getScore(), player.getCredit());

            long masterBeforeScore = master.getScore();
            long masterAfterScore = master.getScore() + finalCredit;
            master.setScore(masterAfterScore);
            log.error("庄家:{}之前的积分为:{},之后的积分为{}", master.getUser().getName(), masterBeforeScore, masterAfterScore);
            long followerBeforeScore = player.getScore();
            long followerAfterScore = player.getScore() + -1 * finalCredit;
            player.setScore(followerAfterScore);
            log.info("闲家:{}之前的积分为:{},之后的积分为{}", player.getUser().getName(), followerBeforeScore, followerAfterScore);
        }
    }

    /**
     * @param masterPlayerCredit 庄家的当前积分
     * @param playerCredit       玩家的当前积分
     * @param credit             庄家赢的积分，正数是赢 负数是输
     * @return
     */
    public static int calFinalCredit(long masterPlayerCredit, long playerCredit, int credit) {

        long finalCredit = 0;
        if (credit >= 0) {
            //庄家赢，计算能够赢闲家多少积分
            finalCredit = playerCredit - credit >= 0 ? credit : playerCredit;
        } else {
            //庄家输，计算能够输闲家多少积分
            finalCredit = masterPlayerCredit + credit >= 0 ? credit : masterPlayerCredit*-1;
        }
        return (int) finalCredit;
    }

    @Test
    public void tests(){
        calFinalCredit(10,0,20);
    }

}
